const XOR_CODE = 23442827791579n;
const MASK_CODE = 2251799813685247n;
const MAX_AID = 1n << 51n;
const BASE = 58n;

const data = 'FcwAPNKTMug3GV5Lj7EJnHpWsx4tb8haYeviqBz6rkCy12mUSDQX9RdoZf';

function av2bv(aid) {
  const bytes = ['B', 'V', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0'];
  let bvIndex = bytes.length - 1;
  let tmp = (MAX_AID | BigInt(aid)) ^ XOR_CODE;
  while (tmp > 0) {
    bytes[bvIndex] = data[Number(tmp % BigInt(BASE))];
    tmp = tmp / BASE;
    bvIndex -= 1;
  }
  [bytes[3], bytes[9]] = [bytes[9], bytes[3]];
  [bytes[4], bytes[7]] = [bytes[7], bytes[4]];
  return bytes.join('');
}

function bv2av(bvid) {
  const bvidArr = Array.from(bvid);
  [bvidArr[3], bvidArr[9]] = [bvidArr[9], bvidArr[3]];
  [bvidArr[4], bvidArr[7]] = [bvidArr[7], bvidArr[4]];
  bvidArr.splice(0, 3);
  const tmp = bvidArr.reduce((pre, bvidChar) => pre * BASE + BigInt(data.indexOf(bvidChar)), 0n);
  return Number((tmp & MASK_CODE) ^ XOR_CODE);
}

//console.log(av2bv(111298867365120));
//console.log(bv2av('BV1L9Uoa9EUx'));
function add2DOM(res)
{
  // 创建一个新的 div 元素
  let newDiv = document.createElement("div");
  // 给它一些内容
  let newContent = document.createTextNode(res);
  // 添加文本节点 到这个新的 div 元素
  newDiv.appendChild(newContent);
  // 将这个新的元素和它的文本添加到 DOM 中
  let currentDiv = document.getElementById("result");
  currentDiv.appendChild(newDiv);

  //currentDiv.insertAdjacentHTML("beforeend", newDiv);
  //document.body.insertBefore(newDiv, currentDiv);
}


function onButtonAv2Bv()
{
  let box= document.getElementById("VideoId");
  add2DOM(av2bv(box.value));
}


function onButtonBv2Av()
{
  let box= document.getElementById("VideoId");
  add2DOM(bv2av(box.value));
}